package com.filldream.fastboot.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.websocket.Session;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * WebSocket工具类
 * @author RickSun
 */
@Slf4j
public class WsUtil {

    /**
     * 获取ws连接的参数
     * @param session
     * @return
     */
    public static List<String> getPathParts(Session session) {
        if( session != null ){
            URI requestURI = session.getRequestURI();
            String path = requestURI.getPath();
            String[] parts = path.replaceFirst("^/", "").split("/");
            return Arrays.asList( parts );
        }
        return Collections.emptyList();
    }

    /**
     * 判断是否在线
     * @param session   WebSocket连接Session
     * @return        是否在线 true：在线 false：离线
     */
    public static Boolean isOnline(Session session){
        return session!= null && session.isOpen();
    }

    /**
     * 发送文本消息消息
     * @param session WebSocket连接Session
     * @return  0-不在线 1-发送成功 2-发送失败
     */
    public static Integer sendText(Session session,String message){
        if(isOnline(session)) {
            try {
                session.getBasicRemote().sendText(message);
                return 1;
            } catch (IOException e) {
                log.error("WsSessionSend异常1==>", e);
                return 2;
            } catch (Exception e) {
                log.error("WsSessionSend异常2==>", e);
                return 2;
            }
        }
        return 0;
    }

    /**
     * 关闭WebSocket连
     * @param session   WebSocket连接Session
     * @param closeMsg  关闭消息,为空不发送消息，直接关闭
     */
    public static void close(Session session, String closeMsg) {
        if(isOnline(session)) {
            if(StringUtils.isNotBlank(closeMsg)){
                sendText(  session, closeMsg );
            }
            try {
                session.close();
            } catch (IOException e) {
                log.error("WsSessionClose异常1==>", e);
            }
        }
    }

}
